package com.geek.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.geek.boot.entity.User;
import com.geek.boot.result.Result;
import com.geek.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/9/8
 *
 * 单表CRUD
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //增加用户信息
    @PostMapping
    public Result save(@RequestBody User user){
        boolean flag = userService.save(user);
        if(flag){
            return new Result(true , "用户插入成功" , user);
        }
        return new Result(false , "用户插入失败");
    }

    //查询用户列表信息
    @GetMapping
    public Result findList(String query){
        //封装查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(query) , User::getUsername , query);
        //执行查询
        List<User> list = userService.list(wrapper);
        if(!CollectionUtils.isEmpty(list)){
            return new Result(true , "查询用户列表成功" , list);
        }
        return new Result(false , "查询用户列表失败");
    }


    //查询单个用户信息
    @GetMapping("{id}")
    public Result findById(@PathVariable("id") Integer id){
        User user = userService.getById(id);
        if(user!=null){
            return new Result(true , "用户查询成功" , user);
        }
        return new Result(false , "用户查询失败");
    }

    //修改用信息
    @PostMapping("update")
    public Result update(@RequestBody User user){
        boolean flag = userService.updateById(user);
        if(flag){
            return new Result(true , "用户更新成功" , user);
        }
        return new Result(false , "用户更新失败");
    }

    //删除用户信息
    @GetMapping("del/{id}")
    public Result del(@PathVariable("id")Integer id){
        boolean flag = userService.removeById(id);
        if(flag){
            return new Result(true , "删除成功");
        }
        return new Result(false , "删除失败");
    }


}
